<?php
namespace api\modules\v1\models\shop;

use api\modules\common\models\User;
use api\modules\v1\models\user\UserAttention;
use api\modules\v1\models\userLevel\UserLevel;
use common\models\CacheKeys;
use common\models\Functions;
use common\models\shop\Goods;
use common\models\Status;
use common\models\user\UserUnusualLog;
use yii\base\Exception;
use Yii;
use yii\helpers\ArrayHelper;

/**
 * This is the model class for table "project_info".
 *
 * @property int $id
 * @property string $name
 */
class GoodsInfo extends Goods

{

    public function rules()
    {
        return [
            [['deputy_image','price','old_price','content','category_id','num'],'required','message' => "{attribute}不能为空", 'on' => ['addEdit']],//两个值必须有
        ];
    }

    public function attributeLabels()
    {
        return [
//            'name' => '商品名称',
            'deputy_image' => '副图',
            'price' => '价格',
            'old_price' => '原价',
            'content' => '内容',
            'category_id' => '分类id',
            'num' => '库存',
            'sale_nums' => '销量',
            'freight' => '运费',
        ];
    }

    /**
     * 设置场景
     * @return array
     */
    public function scenarios()
    {
        $scenarios = [
            'addEdit' => ['name','deputy_image','price','old_price','content','category_id', 'num', 'sale_nums','freight'],
        ];
        return array_merge(parent::scenarios(), $scenarios);
    }

    /**
     * 商品列表
     * @param int $page
     * @param int $size
     * @return array
     */
    public function getGoodsList() {
        try {

//            $userInfo = Yii::$app->getUser()->getIdentity()->toArray();
            $userInfo = (new User())->checkUserNoExp();

            $levelInfo = [];
            if ($userInfo) {
                $levelInfo = UserLevel::getOneInfoById($userInfo['level_id']);
            }

            $page = Yii::$app->request->get('page',1);
            $size = Yii::$app->request->get('size',20);
            $categoryId = Yii::$app->request->get('category_id','');
            $goodsName = Yii::$app->request->get('name','');
            $my = Yii::$app->request->get('my','');
            $status = Yii::$app->request->get('status','');
            $type = Yii::$app->request->get('type','');
            $txCode = Yii::$app->request->get('tx_code','');

            $andWhere = $where = [];
            $where['status'] = Status::COMMON_RADIO_YES;
//            $where['is_sell'] = Status::COMMON_RADIO_YES;
            $where['is_delete'] = Status::COMMON_RADIO_YES;
            $where['check_status'] = Status::COMMON_CHECKING_SUCCESS;
            if ($my) {
                if (empty($userInfo)) {
                    throw new Exception('请先登录',1002);
                }
                $where['user_id'] = $userInfo['id'];
                $where['status'] = $status;
//                unset($where['is_sell']);
            }
            if ($type) {
                $where['type'] = $type;
            }
            if ($categoryId) {
                $where['category_id'] = $categoryId;
            }

            if ($txCode) {
                $searchUser = User::getOneByWhere(['tx_code' => $txCode]);
                $where['user_id'] = $searchUser['id'];
            }

            if ($goodsName) {
                $andWhere[] = ['like', 'content', $goodsName];
            }
            
            $closeUserList = User::getByAndWhere(['is_delete' => 2 , 'status' => 2]);
            $closeIds = array_column($closeUserList,'id');

            if ($closeIds) {
                $andWhere[] = ['not in','user_id',$closeIds];
            }


            list($longitude,$latitude) = $this->getPosition($userInfo['phone']);
            $distanceField = "ROUND(
                6378.138 * 2 * ASIN(
                    SQRT(
                        POW(
                            SIN(
                                (
                                    {$latitude} * PI() / 180 - latitude * PI() / 180
                                ) / 2
                            ),
                            2
                        ) + COS({$latitude} * PI() / 180) * COS(latitude * PI() / 180) * POW(
                            SIN(
                                (
                                    {$longitude} * PI() / 180 - longitude * PI() / 180
                                ) / 2
                            ),
                            2
                        )
                    )
                ),5 
            ) AS distance";

            $count = static::getCountByAndWhere($where,$andWhere);
            $offset = ($page - 1) * $size;
            $data = $this->setPageinationAPI($page, $size, $count);

            $order = 'distance ASC';
            $list = static::getObjectByAndWhere($where,$andWhere,['*',$distanceField],$order,$offset,$size)->with('user')->asArray()->all();

            $result = [];
            foreach($list as &$v) {
//                $deputyImage = json_decode($v['deputy_image'],true);
//                $images = [];
//                foreach($deputyImage as &$vv){
//                    $images[] = $this->getImages($vv);
//                }

                $deputyImage = static::getAllImagesWithType($v['deputy_image']);
                $images = [];
                foreach($deputyImage as &$vv){
                    if ($vv['type'] == 1) {
                        $images[] = $vv['url'];
                    }
                }
                $tmp = [
                    'id' => (int) $v['id'],
                    'nick_name' => $v['user']['nick_name']?:'',
                    'user_face' => $this->getImages($v['user']['user_face'])?:'',
//                    'name' => $v['name'],
                    'name' => $v['content'],
                    'image' =>  $images['0'],
                    'price' => $v['price'] ?:'',
                    'type' => $v['type'] ?:'',
                    'type_name' => Status::GOODS_TYPE_MAP[$v['type']] ?? '',
                    'like_nums' => $v['like_nums'],
                    'status' => $v['status'],
                    'num' => $v['num'],
                    'sale_num' => $v['sale_nums'] ?: 0,
                    'distance' => round($v['distance'],2),
                ];

                $tmp['distance'] = \api\modules\v1\models\user\User::handleDistance($levelInfo,$v['user'],$tmp['distance']);


//                if($levelInfo && $levelInfo['show_nearby'] == Status::COMMON_RADIO_NO ){
//                    $tmp['distance'] = ">100KM";
//                } else {
////                    $tmp['distance'] = $userInfo && $tmp['distance'] ? $tmp['distance'].'KM' : '未知';
//                    $tmp['distance'] = $tmp['distance'].'KM';
//                }

                unset($images);
                $result[] = $tmp;
            }

            $data['data'] = $result;
            return Functions::formatRestAPI(0, '', $data);
        } catch (Exception $e) {
            return Functions::formatRestAPI(1, $e->getMessage());
        }
    }

    /**
     * 商品goods详情
     * @param int $id
     * @param int $detailId
     * @return array
     */
    public function getInfo($id = 0) {
        try {
//            $userInfo = Yii::$app->getUser()->getIdentity()->toArray();
            $userInfo = (new User())->checkUserNoExp();
            if (empty($id)) {
                throw new Exception('未知信息');
            }

            $where['id'] = $id;
            $where['status'] = Status::COMMON_RADIO_YES;
//            $where['is_sell'] = Status::COMMON_RADIO_YES;
            $where['is_delete'] = Status::COMMON_RADIO_YES;
            $where['check_status'] = Status::COMMON_CHECKING_SUCCESS;
            $info = static::getObjectOneByWhere($where)->with([
                'user' => function ($q) {
                    $q -> select(['id','login_name','nick_name','user_face','tx_code']);
                },
            ])->asArray()->one();

            if (empty($info)) {
                throw new Exception('未知商品信息');
            }
            $return = [];

//            $deputyImage = json_decode($info['deputy_image'],true);
//            foreach($deputyImage as &$v){
//                $images[] = static::getImages($v);
//            }

            $deputyImage = static::getAllImagesWithType($info['deputy_image']);
//            $images = [];
//            foreach($deputyImage as &$v){
//                if ($v['type'] == 1) {
//                    $images[] = $v['url'];
//                }
//            }
            $singleUserInfo = ArrayHelper::getValue($info,'user',[]);
            $return = [
                'id' => $info['id'],
                'user_id' => $info['user_id'],
                'name' => $info['name'],
                'deputy_image' => $deputyImage ?? [],
                'content' => $info['content'],
                'create_time' => $info['create_time'],
                'price' => $info['price'],
                'old_price' => $info['old_price'],
                'comment_nums' => $info['comment_nums'],
                'collect_nums' => $info['collect_nums'],
                'view_nums' => $info['view_nums'],
                'like_nums' => $info['like_nums'],
                'type' => $info['type'],
                'num' => $info['num'],
                'type_name' => Status::GOODS_TYPE_MAP[$info['type']],
                'freight' => floatval($info['freight']),
            ];

            //是否关注
            $isAttention = 2;
            if ($userInfo) {
                $followList = UserAttention::getByAndWhere(['user_id' => $userInfo['id'],'type'=>Status::USER_ATTENTION_TYPE_FOLLOW]);
                $followIds = array_column($followList,'topic_id');
                if(in_array($singleUserInfo['id'],$followIds)){
                    $isAttention = 1;
                }else{
                    $isAttention = 2;
                }
                if($singleUserInfo['id'] == $userInfo['id'] ){
                    $isAttention = 3;
                }
            }

            $return['is_attention'] = $isAttention;

            // 收藏
            $isCollect = false;
            if ($userInfo) {
                $collect = GoodsCollection::getOneByWhere(['user_id' => $userInfo['id'],'goods_id' => $id]);
                $isCollect = $collect ? true : false;
            }

            $return['is_collect'] = $isCollect;
            $return['user'] = [
                'id' => $info['user']['id']?:"",
                'login_name' => $info['user']['login_name']?:"",
                'nick_name' => $info['user']['nick_name']?:"",
                'user_face' => static::getImages($info['user']['user_face'])?:"",
                'tx_code' => $info['user']['tx_code']?:"",
            ];

            //增加浏览量
            static::updateAllCounters(['view_nums' => 1],['id' => $id]);

            return Functions::formatRestAPI(0, '', $return);
        } catch (\yii\db\Exception $ee) {
            return Functions::formatRestAPI(1, '数据异常');
        } catch (Exception $e) {
            return Functions::formatRestAPI(1, $e->getMessage());
        }
    }

    /**
     * 收藏商品
     * @param $id int 动态Id
     * @return array
     */
    public function collect($id = 0) {
        $trans = Yii::$app->db->beginTransaction();
        try {
            $userInfo = Yii::$app->getUser()->getIdentity()->toArray();
            $userId = $userInfo['id'];
            $id = (int) $id;
            if (empty($id)) {
                throw new Exception('请求数据有误');
            }
            //获取用户Id
            $goodsInfo = GoodsInfo::getOneInfoById($id);
            if(empty($goodsInfo)) {
                throw new Exception('请求数据有误');
            }

            //检查是否存在数据
            $check['goods_id'] = $id;
            $check['user_id'] = $userId;
            $check['type'] = 1;
            $checkRes = GoodsCollection::getOneByWhere($check);

            $returnData = [];
            if (!empty($checkRes)) {
                $msg = '取消收藏失败';
                //存在就删除
                $res = GoodsCollection::deleteAll($check);
                if ($res === false) {
                    throw new Exception($msg);
                }

                //点赞数减一
                $res = static::updateAllCounters(['collect_nums' => -1], ['id' => $id]);
                if ($res === false) {
                    throw new Exception($msg);
                }
                $trans->commit();
                $returnData['is_collection'] = false;
                return Functions::formatRestAPI(0, '取消收藏成功',  $returnData);
            } else {
                $msg = '收藏失败';
                //不存在 添加
                $check['create_time'] = date('Y-m-d H:i:s');
                $res = GoodsCollection::insertData($check);
                if ($res === false) {
                    throw new Exception($msg);
                }

                //点赞数加1
                $res = static::updateAllCounters(['collect_nums' => 1], ['id' => $id]);
                if ($res === false) {
                    throw new Exception($msg);
                }
                $trans->commit();
                $returnData['is_collection'] = true;
                return Functions::formatRestAPI(0,'收藏成功',$returnData);
            }
        } catch (\yii\db\Exception $ee) {
            return Functions::formatRestAPI(1, '数据异常');
        } catch (Exception $e) {
            $trans->rollBack();
            return Functions::formatRestAPI(1, $e->getMessage());
        }
    }

    /**
     * 我想要
     * @param $id int 动态Id
     * @return array
     */
    public function like($id = 0) {
        try {
            $userInfo = Yii::$app->getUser()->getIdentity()->toArray();
            //检查是否存在数据
            $check['goods_id'] = $id;
            $check['user_id'] = $userInfo['id'];
            $check['type'] = 2;
            $checkRes = GoodsCollection::getOneByWhere($check);
            if (empty($checkRes)) {
                static::updateAllCounters(['like_nums' => 1], ['id' => $id]);
                GoodsCollection::insertData($check);
            }

            return Functions::formatRestAPI(0,'喜欢成功');
        } catch (\yii\db\Exception $ee) {
            return Functions::formatRestAPI(1, '数据异常');
        } catch (Exception $e) {
            return Functions::formatRestAPI(1, $e->getMessage());
        }
    }

    /**
     * 获取修改信息
     * @param int $id
     * @return array
     */
    public function getGoodsInfo($id = 0) {
        try {
            $userInfo = Yii::$app->getUser()->getIdentity()->toArray();
            if (empty($id)) {
                throw new Exception('未知信息');
            }
            $where['id'] = $id;
            $where['user_id'] = $userInfo['id'];
//            $where['type'] = Status::GOODS_TYPE_NAME_PERSONAL;
            $info = static::getObjectOneByWhere($where,'*')->with([
                'category'=> function($q){
                    $q->select(['id','name']);
                }
            ])->asArray()->one();
            if (empty($info) || $info['is_delete'] == Status::COMMON_RADIO_NO) {
                throw new Exception('该商品不存在！');
            }
            if($userInfo['id'] != $info['user_id']){
                throw new Exception('这不是您发布的商品！');
            }
//            $deputy_image = json_decode($info['deputy_image'],true);
//            foreach($deputy_image as &$v){
//                $images[] = static::getImages($v);
//            }
            $deputyImage = static::getAllImagesWithType($info['deputy_image']);
//            $images = [];
//            foreach($deputyImage as &$v){
//                if ($v['type'] == 1) {
//                    $images[] = $v['url'];
//                }
//            }
            $info['deputy_image'] = $deputyImage?:[];

            return Functions::formatRestAPI(0, '', $info);
        } catch (Exception $e) {
            return Functions::formatRestAPI(1, $e->getMessage());
        }
    }

    /**
     * 商品添加修改
     * @return array
     * ["multiple/f9535b959f7f31fbf5028e7872eb6982.jpg","multiple/f9535b959f7f31fbf5028e7872eb6982.jpg"]
     */
    public function addEditGoods() {
        $trans = \Yii::$app->db->beginTransaction();
        try {
            $userInfo = Yii::$app->getUser()->getIdentity()->toArray();

            CacheKeys::checkFrequency($userInfo['id'],1);

            //判断当前用户状态
            UserUnusualLog::checkUserUnusual($userInfo['id'],Status::USER_UNUSUAL_TYPE_GOODS);

            if (!$this->validate()) {
                throw new Exception($this->getErrorSummary(true)[0]);
            }

            $currentLevelInfo = UserLevel::getOneByWhere(['id' => $userInfo['level_id']]);
            if ($currentLevelInfo['is_issue_goods'] == Status::COMMON_RADIO_NO) {
                throw new Exception('当前级别不可发布橱窗商品！');
            }
            $wordNum = mb_strwidth($this->content);
            if ($currentLevelInfo['greet_limit']) {
                if ($wordNum >= $currentLevelInfo['goods_word_limit']) {
                    throw new Exception('当前级别橱窗介绍文字上限为'.$currentLevelInfo['goods_word_limit'].'！');
                }
            }

            $post = Yii::$app->request->post();
            $id = (int)Yii::$app->request->post('id','');

            $data= [];
            $data = array_merge($data, $this->getSaveData($this->scenario, $post));
            $data['deputy_image'] = json_encode($data['deputy_image'],true);
            $data['user_id'] = $userInfo['id'];
            $data['type'] = Status::GOODS_TYPE_NAME_PERSONAL;


            # 判断视频 与 图片个数
            $deputyImage = static::getAllImagesWithType($data['deputy_image']);
            $videoCount = 0;
            $imageCount = 0;
            foreach($deputyImage as &$vv){
                if ($vv['type'] == 1) {
                    $imageCount ++;
                }  else {
                    $videoCount ++;
                }
            }

            if ($videoCount > 1) {
                throw new Exception('只能上传一个视频！');
            }

            if ($imageCount < 1) {
                throw new Exception('最少上传一张图片！');
            }

            if (!empty($id)) {
                //更新操作
                $where['id'] = $id;
                $where['user_id'] = $userInfo['id'];
                $info = static::getOneByWhere($where);
                if (empty($info) || $info['is_delete'] == Status::COMMON_RADIO_NO) {
                    throw new Exception('该商品不存在！');
                }
                if($userInfo['id'] != $info['user_id']){
                    throw new Exception('这不是您发布的商品！');
                }
//                if($userInfo['is_sell'] == Status::COMMON_RADIO_NO){
//                    throw new Exception('商品已经出售，无法修改！');
//                }

                $data['update_time'] = date('Y-m-d H:i:s');
                $res = static::updateData($data, ['id' => $id]);

                if ($res === false) {
                    throw new Exception('更新失败');
                }
                $msg = '修改成功';

            }else{
                //添加操作
                # 位置
                list($longitude,$latitude) = $this->getPosition($userInfo['login_name']);
                if (empty($longitude) || empty($latitude)) {
                    throw new Exception('未获取到位置信息！');
                }
                $data['longitude'] = $longitude;
                $data['latitude'] = $latitude;
                $data['check_status'] = Status::COMMON_CHECKING_SUCCESS;
                $data['create_time'] = $data['update_time']= date('Y-m-d H:i:s');

                if($userInfo['is_service'] == Status::COMMON_RADIO_YES){
                    $goodsType = Yii::$app->request->post('goods_type',0);
                    if (empty($goodsType)) {
                        throw new Exception('请选择商品类型！');
                    }
                    if (!array_key_exists($goodsType,Status::GOODS_TYPE_MAP)) {
                        throw new Exception('商品类型不合法！');
                    }

                    $data['type'] = $goodsType;
                } else {
                    $data['type'] = Status::GOODS_TYPE_NAME_PERSONAL;
                }

                $res = static::insertData($data);
                if ($res === false) {
                    throw new Exception('添加失败');
                }
                $msg = '添加成功';
            }

            $trans->commit();
            return Functions::formatRestAPI(0, $msg);
        } catch (Exception $e) {
            $trans->rollBack();
            return Functions::formatRestAPI(1, $e->getMessage());
        }
    }

    /**
     * 上下架
     * @param int $id
     * @return array
     */
    public function getGoodsStatus() {
        try {
            $userInfo = Yii::$app->getUser()->getIdentity()->toArray();
            $goodsId = (int)Yii::$app->request->get('goods_id','');
            $status = (int)Yii::$app->request->get('status','');
            if (empty($goodsId)) {
                throw new Exception('未知信息');
            }
            if (empty($status)) {
                throw new Exception('未知状态');
            }
            $where['id'] = $goodsId;
            $where['user_id'] = $userInfo['id'];
//            $where['type'] = Status::GOODS_TYPE_NAME_PERSONAL;
            $info = static::getObjectOneByWhere($where,'*')->with([
            ])->asArray()->one();
            if (empty($info) || $info['is_delete'] == Status::COMMON_RADIO_NO) {
                throw new Exception('该商品不存在！');
            }

//            if ($info['type'] != Status::GOODS_TYPE_NAME_PERSONAL) {
//                throw new Exception('该商品是商家商品，不能下架！');
//            }

            if($userInfo['id'] != $info['user_id']){
                throw new Exception('这不是您发布的商品！');
            }

            $up['status'] = $status;
            $res = static::updateData($up,['id'=>$goodsId]);
            if($res == false){
                throw new Exception('操作失败！');
            }

            return Functions::formatRestAPI(0, '操作成功');
        } catch (Exception $e) {
            return Functions::formatRestAPI(1, $e->getMessage());
        }
    }




}
